import pymysql
from pyecharts.charts import Pie
from pyecharts import options
# 连接数据库
db = pymysql.connect(
    host="localhost",
    user="root",
    password="040814",
    database="crawlerdemo",
    charset="utf8"
)
cursor = db.cursor()
# 用来查找岗位数量最多的五个城市
# 计算总数量的SQL查询
total_sql = "SELECT COUNT(job_id) AS total_count FROM job"
cursor.execute(total_sql)
total_count = cursor.fetchone()[0]

# 修改主查询以获取每个job_place的占比，注意这里简化了直接在Python中计算占比的逻辑
sql = (
    "SELECT job_place, COUNT(job_id) * 100.0 / %s AS percentage "
    "FROM job "
    "GROUP BY job_place "
)
try:
    cursor.execute(sql, (total_count,))
    res = cursor.fetchall()
    pie = Pie()
    # [("类型1",30),("类型2",40),......]
    pie.add("百分之", res)
    pie.set_global_opts(title_opts=options.TitleOpts(title="各城市岗位占比图"))
    pie.render("piera.html")
except:
    print("查询出错啦")
